#!/usr/bin/python2
# -*- coding: UTF-8 -*-

import logging
import urllib2
import urllib
import sys
import os
import re
import json
import codecs
import copy
import ConfigParser

class BaiduMap:
    def __init__(self, baidu_key):
        # baidu key
        self.baidu_key = baidu_key
        #self.baidu_key = '3m5x1swO4NazGPfjshFV0rm7zDLtP81a'
        # 参数设置
        # 取值为1 或空，则返回基本信息；取值为2，返回检索POI详细信息
        self.scope = 1
        # 范围记录数量，默认为10条记录，最大返回20条。多关键字检索时，返回的记录数为关键字个数*page_size。
        self.page_size = 20
        pass

    def __del__(self):
        pass

    # @brief 查询接口
    # @param [in]regin: city name
    # @param [in]query_key: keywords
    # @return query cout
    def query_baidu_map(self, region, query_key, timeout):
        result_list = []
        title = ['名字', '地址', '电话', '经营类型', '标签']
        count = 0
        page_num = 0
        while True:
            url = "http://api.map.baidu.com/place/v2/search?q=%s&region=%s&output=json&scope=%d&page_size=%d&page_num=%d&ak=%s" % (query_key, region, self.scope, self.page_size, page_num, self.baidu_key)
            try:
                response = urllib2.urlopen(url, timeout=timeout)
                html = response.read().decode('utf-8')
                result_json = json.loads(html)
                if result_json["message"] != "ok" or result_json['total'] == 0:
                    break

                result_list.append(result_json['results'])
                count += len(result_json['results'])
                page_num = page_num + 1
            except Exception, error:
                logging.error('error: %s', error)
                break

        recording_list = []
        for result in result_list:
            for item in result:
                name = ''
                address = ''
                telephone = ''
                type = ''
                tag = ''

                try:
                    name = item['name'].encode(encoding='UTF-8', errors='strict')
                except Exception, error:
                    pass

                try:
                    address = item['address'].encode(encoding='UTF-8', errors='strict')
                except Exception, error:
                    pass

                try:
                    telephone = item['telephone'].encode(encoding='UTF-8', errors='strict')
                except Exception, error:
                    pass

                try:
                    type = item['detail_info']['type'].encode(encoding='UTF-8', errors='strict')
                except Exception, error:
                    pass

                try:
                    tag = item['detail_info']['tag'].encode(encoding='UTF-8', errors='strict')
                except Exception, error:
                    pass

                recording_list.append((name, address, telephone, type, tag))
            pass

        return count, title, recording_list

if __name__ == "__main__":
    pass
else:
    pass